import Vue from 'vue'
import app from './App.vue'
import MintUI from 'mint-ui'
import VueRouter from 'vue-router'
import './lib/mui/css/mui.min.css'
import './lib/mui/css/icons-extra.css'
import router from './router.js'
import VueResource from 'vue-resource'
import moment from 'moment'
import axios from '../node_modules/axios'
import VuePreview from 'vue-preview'
import 'mint-ui/lib/style.css'
import Vuex from 'vuex'
Vue.prototype.$axios = axios;
Vue.use(MintUI)
Vue.use(VueRouter)
Vue.use(VueResource)
Vue.use(VuePreview)
Vue.use(Vuex)
//全局过滤器
Vue.filter('dateFormat',function(dateStr,pattern="YYYY-MM-DD HH:mm:ss"){
  return moment(dateStr).format(pattern)
})
Vue.http.options.emulateHTTP = true;
Vue.http.options.emulateJSON = true;
Vue.http.options.headers = {
'Content-Type':'application/json;charset=UTF-8'
}

var goods = JSON.parse(sessionStorage.getItem('goods') || '[]')
//vuex配置
const store = new Vuex.Store({
  state : {
    goods:goods,
    //[// 格式{id:,count:,price:,selected:,title}],
    num : 1,
  },
  mutations : {
    addToCar(state,goodsinfo){
      //如果有 只更新数据
      //如果没有 push到car中 即可
      var flag = false;  //假设没有找到对应的商品
      state.goods.some( item => {
        if(item.id==goodsinfo.id){
          item.count+=parseInt(goodsinfo.count);
          flag = true
          return true
        }
      })

      if(!flag){
        state.goods.push(goodsinfo);
      }

      //当 更新car 后，把car数组，存储到本地的localstorage/sessionstorage中
      sessionStorage.setItem('goods',JSON.stringify(state.goods))
    },
    updatedGoodsInfo(state,goodsinfo) {
      state.goods.some(item=>{
        if(item.id == goodsinfo.id){
          item.count = parseInt(goodsinfo.count)
          return true;
        }
      })
      sessionStorage.setItem('goods',JSON.stringify(state.goods));  
    },
    remove(state,id){
      state.goods.some((item,i) => {
        if(item.id==id){
          state.goods.splice(i,1)
          return true
        }
      });

      sessionStorage.setItem('goods',JSON.stringify(state.goods))
    },
    change(state,id){
      state.goods.some((item)=>{
        if(item.id==id){
          item.selected = !item.selected
          return true
        }
      })

      sessionStorage.setItem('goods',JSON.stringify(state.goods));
    }
  },
  getters : {
    getAllCount(state){
      var c = 0;
      state.goods.forEach(item => {
        c+=item.count
      })
      return c;
    },
    sum(state){
      var o={
        num : 0,
        sum : 0
      } 
      state.goods.forEach(item=>{
        if(item.selected){
          o.num+=item.count;
          o.sum+=item.count*item.price
        }
      })
      return o;
    }
  }
})
//export default store
var vm = new Vue({
  el:'#app',
  render:c=>c(app),
  router,
  axios,
  store
})
/*
var express = require('express')
var app = express()
var data = require('../static/data.json');
var apiRoutes = express.Router();
apiRoutes.post()*/